import { FC, useEffect } from 'react'
import { useRoutes, useNavigate, useLocation } from 'react-router-dom'
import storage from '../utils/storage'

type Iprops = {
    tokenKey: string,
    routes: RouteObj[]
}


// #FF0000 路由守卫  相当于beforeEach
const useRouterwithGuard: FC<Iprops> = (props) => {
    ////获取本地token
    let token = storage.get('lh-token')
    let location = useLocation()
    let navigate = useNavigate()

    useEffect(() => {
        ////判断token
        if (!token) {
            // console.log(location);
            ////判断访问的是不是login  如果不是就跳转到login
            if (location.pathname !== '/login') {
                navigate('/login')
            }
        }
    },[location.pathname])

    let { routes, tokenKey } = props

    let element = useRoutes(routes)

    return element
}

export default useRouterwithGuard